package com.pc.controller;

import java.io.IOException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.pc.service.ReceiveMsgServicePc_1;
import com.pc.util.log.LogWrite;
import com.pc.util.rabbitmq.RabbitmqConnection;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConsumerCancelledException;
import com.rabbitmq.client.QueueingConsumer;
import com.rabbitmq.client.QueueingConsumer.Delivery;
import com.rabbitmq.client.ShutdownSignalException;

@Controller
public class ReceiveMsgController {
	
	@Autowired
	private RabbitmqConnection rabbitmqConnection;
	@Autowired
	private ReceiveMsgServicePc_1 rms1;
	
	
	@RequestMapping("receiveMsg1")
	public void receive1() {
		LogWrite.trace(ReceiveMsgController.class,"一号消费者等待接收消息");
		// 获取连接
		Connection conn = rabbitmqConnection.getConn();
		try {
			Channel chan = conn.createChannel();
			// 声明队列
			chan.queueDeclare("direct01", false, false, false, null);
			// 声明交换机
			chan.exchangeDeclare("directEx", "direct");
			// 绑定队列到交换机
			// 参数 1 队列名称,2 交换机名称 3 路由key
			chan.queueBind("direct01", "directEx", "pc01");
			chan.basicQos(1);
			// 定义消费者
			QueueingConsumer consumer = new QueueingConsumer(chan);
			// 消费者与队列绑定
			chan.basicConsume("direct01", false, consumer);
			while (true) {
				Delivery delivery = consumer.nextDelivery();
				String url = new String(delivery.getBody());
				LogWrite.warn(ReceiveMsgController.class,"一号消费者接收到" + url);
				String result = rms1.sayHiFromClientOne(url);
				LogWrite.trace(ReceiveMsgController.class,"一号消费者返回值result=" + result);
				chan.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
			}
		} catch (ShutdownSignalException e) {
			e.printStackTrace();
		} catch (ConsumerCancelledException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}finally {
			
		}
	}
	
	
}
